﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Phone.Excel;
using System.Globalization;
using System.IO.IsolatedStorage;
using System.IO;
using System.Net.Browser;
using System.Text;
using System.ComponentModel;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Microsoft.Phone.Tasks;
using System.Threading;

namespace ControlExplorer.Controls.Excel
{
    public partial class DemoExcel : UserControl
    {
        public DemoExcel()
        {
            InitializeComponent();
        }

        private void btnHelloWorld_Click(object sender, RoutedEventArgs e)
        {
            loadingGrid.Visibility = System.Windows.Visibility.Visible;
            UploadBookToWL("Hello World.xlsx", book =>
            {
                book.Sheets[0][0, 0].Value = "Hello World";
            });
        }

        private void btnStyles_Click(object sender, RoutedEventArgs e)
        {
            loadingGrid.Visibility = System.Windows.Visibility.Visible;
            UploadBookToWL("Styles.xlsx", book =>
            {
                // get the sheet that was created by default, give it a name
                var sheet = book.Sheets[0];

                // create styles for odd and even values
                var styleOdd = new XLStyle(book);
                styleOdd.Font = new XLFont("Tahoma", 9, false, true);
                styleOdd.ForeColor = Colors.Blue;

                var styleEven = new XLStyle(book);
                styleEven.Font = new XLFont("Tahoma", 9, true, false);
                styleEven.ForeColor = Colors.Red;
                styleEven.BackColor = Colors.Yellow;

                // step 3: write content and format into some cells
                for (int i = 0; i < 30; i++)
                {
                    XLCell cell = sheet[i, 0];
                    cell.Value = i + 1;
                    cell.Style = ((i + 1) % 2 == 0) ? styleEven : styleOdd;
                }
            });
        }

        private void btnFormulas_Click(object sender, RoutedEventArgs e)
        {
            loadingGrid.Visibility = System.Windows.Visibility.Visible;
            UploadBookToWL("Formulas.xlsx", book =>
            {
                // first sheet
                var sheet = book.Sheets[0];

                // column width in twips
                sheet.Columns[0].Width = 2000;
                sheet.Columns[1].Width = 2200;

                // string formulas
                string s = "String:";
                sheet[0, 0].Value = s;
                sheet[1, 0].Value = s;
                sheet[2, 0].Value = s;

                sheet[0, 1].Value = "apples";
                sheet[1, 1].Value = "and";
                sheet[2, 1].Value = "oranges";

                s = "String formula:";
                sheet[4, 0].Value = s;
                sheet[5, 0].Value = s;

                sheet[4, 1].Value = "apples and oranges";
                sheet[5, 1].Value = "apples an";
                sheet[4, 1].Formula = "CONCATENATE(B1,\" \",B2, \" \",B3)";
                sheet[5, 1].Formula = "LEFT(B5,9)";

                // simple formulas
                sheet[7, 0].Value = "Formula: 5!";
                sheet[7, 1].Value = 120;
                sheet[7, 1].Formula = "1*2*3*4*5";

                sheet[8, 0].Value = "Formula: 12/0";
                sheet[8, 1].Value = 0;
                sheet[8, 1].Formula = "12/0";

                sheet[9, 0].Value = "Formula: 1 = 1";
                sheet[9, 1].Value = true;
                sheet[9, 1].Formula = "1=1";

                sheet[10, 0].Value = "Formula: 1 = 2";
                sheet[10, 1].Value = false;
                sheet[10, 1].Formula = "1 = 2";

                // now function
                sheet[12, 0].Value = "Formula: Now()";
                sheet[12, 1].Value = DateTime.Now;
                sheet[12, 1].Formula = "Now()";

                var style = new XLStyle(book);
                var dtfi = CultureInfo.CurrentCulture.DateTimeFormat;
                style.Format = XLStyle.FormatDotNetToXL(dtfi.ShortDatePattern + " " + dtfi.ShortTimePattern);
                sheet[12, 1].Style = style;
            });
        }

        const string FILE_NAME = "c1ExcelTest.xlsx";
        const string HTML_PART1 = "<html><head></head><body><a href=\"data:application/vnd.ms-excel;base64,";
        const string HTML_PART2 = "\">Open Excel File</a></body></html>";

        private void SaveBook(Action<C1XLBook> action)
        {
            try
            {
                var book = new C1XLBook();
                if (action != null)
                {
                    action(book);
                }

                // save Excel content in base64
                string excelBase64 = "";
                using (var memoryStream = new MemoryStream())
                {
                    book.Save(memoryStream);
                    memoryStream.Flush();
                    excelBase64 = Convert.ToBase64String(memoryStream.ToArray());
                }

                // create HTML file with inline Excel content
                // and save it to the IsolatedStorage 
                var file = IsolatedStorageFile.GetUserStoreForApplication();
                if (file.FileExists(FILE_NAME))
                    file.DeleteFile(FILE_NAME);
                using (var writer = new StreamWriter(file.CreateFile(FILE_NAME)))
                {
                    writer.Write(HTML_PART1);
                    writer.Write(excelBase64);
                    writer.Write(HTML_PART2);
                }

            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }


        }

        #region ** uploading files to windows like - skydrive

        private Action<C1XLBook> createBookActionSaved;
        private string fileNameSaved;
        private OneDriveHelper wlHelper = new OneDriveHelper();

        public async void UploadBookToWL(string fileName, Action<C1XLBook> createBook)
        {
            fileNameSaved = fileName;
            createBookActionSaved = createBook;
            try
            {
                await wlHelper.GetAccessToken(authorizationBrowser);
            }
            catch
            {
                this.loadingGrid.Visibility = Visibility.Collapsed;
                Dispatcher.InvokeAsync(() =>
                {
                    MessageBox.Show("You could not get an access token, please check your internet connection.");
                });
                return;
            }
            this.loadingGrid.Visibility = Visibility.Visible;
            this.loadingText.Text = "Getting folders from SkyDrive...";
            try
            {

                var folders = await wlHelper.GetFolders();
                if (folders.Count == 0)
                {
                    MessageBox.Show("You should have at least a folder to upload the document to.");
                }
                else
                {
                    foldersList.ItemsSource = folders;
                    selectFolder.Visibility = Visibility.Visible;
                }
            }
            catch
            {
            }
        }

        private async void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selFolder = foldersList.SelectedItem as WLFolder;
            if (selFolder != null)
            {
                selectFolder.Visibility = Visibility.Collapsed;

                this.loadingGrid.Visibility = Visibility.Visible;
                this.loadingText.Text = "Uploading file to SkyDrive...";

                var stream = new MemoryStream();
                var book = new C1XLBook();
                createBookActionSaved(book);
                book.Save(stream);
                stream.Flush();

                try
                {
                    var contentType = "application/vnd.ms-excel";
                    var file = await wlHelper.UploadFileToWL(fileNameSaved, contentType, selFolder, stream);
                    this.loadingText.Text = "Getting file link...";
                    // Open Web browser task to see the file
                    var link = await wlHelper.GetFileInfo(file.Id);
                    this.loadingGrid.Visibility = Visibility.Collapsed;
                    var webBrowser = new WebBrowserTask();
                    webBrowser.Uri = new Uri(link.Link, UriKind.Absolute);
                    webBrowser.Show();
                }
                catch
                {
                    this.loadingGrid.Visibility = Visibility.Collapsed;
                    MessageBox.Show("There was an error trying to upload the file to sky drive. Please try again.");
                }
            }
        }

        #endregion
    }
}
